<template>
	<view class="container">
		<uni-popup ref="popup" type="bottom" :safe-area="false" @maskClick="close">
			<loading v-if="isLoading" :height="300"></loading>
			<view class="main" v-if="!isLoading">
				<view class="header u-flex-between">
					<view></view>
					<view class="title">请选择地址</view>
					<uni-icons type="closeempty" size="20" color="#666666" @click="close"></uni-icons>
				</view>
				<view class="tabs u-flex">
					<view class="li" v-for="(val, index) in visibleTabs" :key="index"
						:class="{active: currentLevel === index}" @click="handleTabClick(index)">
						{{val || '请选择'}}
					</view>
				</view>
				<view class="scroll-view">
					<scroll-view scroll-y="true" class="scroll-Y">
						<view class="box u-flex-between" v-for="(item,index) in currentOptions" :key="item.id"
							@click="handleSelect(item)">
							<span class="text">{{item.area_name}}</span>
							<uni-icons type="checkmarkempty" size="22" color="#000000"
								v-if="isSelected(item)"></uni-icons>
						</view>
					</scroll-view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import { ref, computed, onMounted } from 'vue';
	import { apiGetTreeList } from '@/api/address.js'

	const popup = ref(null)
	const isLoading = ref(true)
	const currentLevel = ref(0) // 当前选择的层级 0-省 1-市 2-区
	const selectedItems = ref([null, null, null]) // 已选择的省市区
	const allOptions = ref([]) // 所有选项数据
	const provinceOptions = ref([]) // 省列表
	const cityOptions = ref([]) // 市列表
	const districtOptions = ref([]) // 区列表

	const emit = defineEmits('selected')

	// 计算当前显示的选项
	const currentOptions = computed(() => {
		if (currentLevel.value === 0) return provinceOptions.value
		if (currentLevel.value === 1) return cityOptions.value
		return districtOptions.value
	})

	// 计算顶部显示的已选项
	const visibleTabs = computed(() => {
		return [
			selectedItems.value[0]?.area_name || '请选择省份',
			selectedItems.value[0] ? (selectedItems.value[1]?.area_name || '请选择城市') : null,
			selectedItems.value[1] ? (selectedItems.value[2]?.area_name || '请选择区县') : null
		].filter(Boolean) // 过滤掉null值
	})

	const open = (selectedAddress) => {
		popup.value.open()
		// 如果有传入已选地址，则进行回显
		if (selectedAddress) {
			initSelection(selectedAddress)
		} else {
			resetSelection()
			if (!provinceOptions.value.length) {
				getTreeList()
			}
		}
	}

	const close = () => {
		popup.value.close()
	}

	const resetSelection = () => {
		currentLevel.value = 0
		selectedItems.value = [null, null, null]
		cityOptions.value = []
		districtOptions.value = []
	}

	// 初始化选中状态（回显用）
	const initSelection = async (selectedAddress) => {
		try {
			isLoading.value = true
			resetSelection()
			if (!provinceOptions.value.length) {
				await getTreeList()
			}
			// 设置省份
			if (selectedAddress.provinceCode) {
				const province = provinceOptions.value.find(p => p.area_id == selectedAddress.provinceCode)
				if (province) {
					selectedItems.value[0] = province
					cityOptions.value = province.child || []
					currentLevel.value = 1

					// 设置城市
					if (selectedAddress.cityCode) {
						const city = cityOptions.value.find(c => c.area_id == selectedAddress.cityCode)
						if (city) {
							selectedItems.value[1] = city
							districtOptions.value = city.child || []
							currentLevel.value = 2

							// 设置区县
							if (selectedAddress.districtCode) {
								const district = districtOptions.value.find(d => d.area_id == selectedAddress
									.districtCode)
								if (district) {
									selectedItems.value[2] = district
								}
							}
						}
					}
				}
			}
		} finally {
			isLoading.value = false
		}
	}

	// 获取省市区数据
	const getTreeList = async () => {
		try {
			const { data } = await apiGetTreeList()
			allOptions.value = data
			provinceOptions.value = data
		} finally {
			isLoading.value = false
		}
	}

	// 处理选择
	const handleSelect = (item) => {
		// 如果当前选择的是省份（第0级），则清除市和区的选择
		if (currentLevel.value === 0) {
			selectedItems.value = [item, null, null] // 保留省份，清除市和区
			cityOptions.value = [] // 清空市列表
			districtOptions.value = [] // 清空区列表
		}
		// 如果当前选择的是市（第1级），则清除区的选择
		else if (currentLevel.value === 1) {
			selectedItems.value = [selectedItems.value[0], item, null] // 保留省和市，清除区
			districtOptions.value = [] // 清空区列表
		}
		// 如果选择的是区（第2级），直接保存
		else {
			selectedItems.value[currentLevel.value] = item
		}
		// 自动切换到下一级（如果有）
		if (currentLevel.value < 2 && item.child?.length) {
			currentLevel.value++
			loadNextLevelOptions()
		} else {
			close()
			emitSelection()
		}
	}

	// 加载下一级选项
	const loadNextLevelOptions = () => {
		const currentItem = selectedItems.value[currentLevel.value - 1]
		if (currentLevel.value === 1) {
			cityOptions.value = currentItem?.child || []
		} else if (currentLevel.value === 2) {
			districtOptions.value = currentItem?.child || []
		}
	}

	// 处理tab点击
	const handleTabClick = (index) => {
		currentLevel.value = index
	}

	// 判断是否已选中
	const isSelected = (item) => {
		const selectedItem = selectedItems.value[currentLevel.value]
		return selectedItem && selectedItem.area_id === item.area_id
	}

	// 向父组件返回选择结果
	const emitSelection = () => {
		const [province, city, district] = selectedItems.value
		const result = {
			province: province?.area_name || '',
			provinceCode: province?.area_id || '',
			city: city?.area_name || '',
			cityCode: city?.area_id || '',
			district: district?.area_name || '',
			districtCode: district?.area_id || '',
			fullAddress: `${province?.area_name || ''} ${city?.area_name || ''} ${district?.area_name || ''}`
				.trim()
		}
		// 这里可以emit事件给父组件
		emit('selected', result)
	}

	// 暴露方法供父组件访问
	defineExpose({
		open
	})
</script>

<style lang="scss" scoped>
	.container {
		.main {
			padding: 0 28rpx;
			height: 800rpx;
			background-color: $base-color-white;
			border-radius: 20rpx 20rpx 0 0;
			overflow: hidden;

			.header {
				padding: 30rpx 0;
				position: relative;

				.title {
					font-size: $font-size-30;
					color: $base-color;
					font-weight: bold;
				}

				.uni-icons {
					position: absolute;
					right: 0;
					top: 30rpx;
				}
			}

			.tabs {
				padding: 30rpx 0 0;

				.li {
					margin-right: 40rpx;
					font-size: $font-size-30;
					color: #999;
					position: relative;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
					width: 100%;
					/* 或者指定一个固定宽度 */

					&.active {
						color: $base-color;
						font-weight: bold;

						&::after {
							content: '';
							position: absolute;
							bottom: -10rpx;
							left: 0;
							width: 100%;
							height: 4rpx;
							background-color: $base-color;
							border-radius: 2rpx;
							display: block;
						}
					}
				}
			}

			.scroll-view {
				height: calc(800rpx - 280rpx); // 减去header和tabs高度

				.scroll-Y {
					height: 100%;
					padding: 20rpx 0;

					.box {
						padding: 20rpx 0;
						border-bottom: 1rpx solid #f5f5f5;

						.text {
							color: $base-product-name-color;
							font-size: $font-size-28;
						}
					}
				}

				.loading-container {
					display: flex;
					justify-content: center;
					align-items: center;
					height: 100%;
				}
			}
		}
	}
</style>